package shuishijie.suishijie.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;


import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import shuishijie.suishijie.R;
import shuishijie.suishijie.model.AlipayInfo;
import shuishijie.suishijie.model.EnvConfig;
import shuishijie.suishijie.model.GvgModel;
import shuishijie.suishijie.model.OrderInfo;
import shuishijie.suishijie.model.ProfitInfo;
import shuishijie.suishijie.model.ShoppingCarInfo;
import shuishijie.suishijie.model.WechartPay;
import shuishijie.suishijie.model.web.BaseResponse;
import shuishijie.suishijie.model.web.RxSubscriber;
import shuishijie.suishijie.util.AppUtil;
import shuishijie.suishijie.util.JsonUtil;
import shuishijie.suishijie.view.ViewSettingItem;

public class OrderPayFragment extends BaseFragment {

    public static final int ALI_PAY_FLAG = 0;

    Unbinder unbinder;
    @BindView(R.id.order_num)
    ViewSettingItem orderNum;
    @BindView(R.id.price)
    ViewSettingItem price;
    @BindView(R.id.pay)
    Button pay;
    @BindView(R.id.wechart)
    RadioButton wechart;
    @BindView(R.id.alipay)
    RadioButton alipay;
    @BindView(R.id.unionpay)
    RadioButton unionpay;
    @BindView(R.id.pay_type)
    RadioGroup payType;
    @BindView(R.id.balance_pay)
    RadioButton balancePay;
    @BindView(R.id.balance_pay_text)
    TextView balancePayText;
    @BindView(R.id.friend_pay_text)
    TextView friendPayText;
    @BindView(R.id.friend_pay)
    RadioButton friendPay;



    private OrderInfo orderInfo;
   // private List<MultipleItem> multipleItems = new ArrayList<>();

    public OrderPayFragment() {
        // Required empty public constructor
    }

    public static OrderPayFragment newInstance(String orderInfo) {
        OrderPayFragment fragment = new OrderPayFragment();
        Bundle args = new Bundle();
        args.putString("orderInfo", orderInfo);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            ShoppingCarInfo[] infos = new ShoppingCarInfo[1];
            orderInfo = JsonUtil.fromJson(args.getString("orderInfo"), OrderInfo.class);
        }
        //GloblaData.setWechartPay(0);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_order_pay, container, false);
        unbinder = ButterKnife.bind(this, view);
      //  init();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
//        if (GloblaData.getWechartPay() == 2) {
//            getActivity().finish();
//        }
    }

    MyHandler mHandler;

    public static class MyHandler extends Handler {
        SoftReference<OrderPayFragment> fragmentSoftReference;

        public MyHandler(OrderPayFragment fragment) {
            this.fragmentSoftReference = new SoftReference<OrderPayFragment>(fragment);
        }

        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ALI_PAY_FLAG:
                    Map<String, String> result = (Map<String, String>) (msg.obj);
                    if (result != null && fragmentSoftReference.get() != null) {
                        int status = AppUtil.parseInt("" + result.get("resultStatus"));
                        String tostMsg = result.get("memo");
                        if (status == 9000) {
                            tostMsg = "支付成功";
                        }
                       // Toast.makeText(fragmentSoftReference.get().getContext(), tostMsg, Toast.LENGTH_LONG).show();
                        if (status == 9000) {
                            fragmentSoftReference.get().getActivity().finish();
                        }
                    }
                    break;
            }
            super.dispatchMessage(msg);
        }
    }

    private void init() {
        mHandler = new MyHandler(this);
        orderNum.setText("订单编号 " + "123456");
        price.setText2(AppUtil.getMoneyStr(orderInfo.getPriceToPay()));
        price.setText2Color(getResources().getColor(R.color.money));


//        GvgModel.getInstance().showIncome()
//                .subscribe(new RxSubscriber<BaseResponse<ProfitInfo>>(this, res -> {
//                    balancePayText.setText("余额支付(可用余额" + AppUtil.getMoneyStr(res.data.availableMoney) + ")");
//                    if (res.data.availableMoney >= orderInfo.getPriceToPay()) {
//                        balancePay.setEnabled(true);
//                    }
//                }));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.pay)
    public void onViewClicked() {
//        if (alipay.isChecked()) {
//            alipay();
//        } else if (wechart.isChecked()) {
//            wechart();
//        } else if (balancePay.isChecked()) {
//            popup = new PasswordInputPopup(getActivity(), orderInfo.getPriceToPay());
//            popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
//            popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//            popup.setListener(p -> {
//                banlancePay(p);
//            });
//            popup.show(pay, Gravity.BOTTOM, 0, 0);
//        } else if (friendPay.isChecked()) {
//            startFriendPay();
//        } else if (unionpay.isChecked()) {
//            onUnionPay();
//        }
    }

    private void onUnionPay() {
//        GvgModel.getInstance().unionAppPay("" + orderInfo.id)
//                .subscribe(new RxSubscriber<BaseResponse<String>>(this, res -> {
//                    /**
//                     * activity —— 用于启动支付控件的活动对象
//                     * spId —— 保留使用，这里输入null
//                     * sysProvider —— 保留使用，这里输入null
//                     * orderInfo —— 订单信息为交易流水号，即TN，为商户后台从银联后台获取。
//                     * mode —— 银联后台环境标识，“00”将在银联正式环境发起交易,“01”将在银联测试环境发起交易
//                     */
//                    String mode = EnvConfig.getCurrentEnv() == EnvConfig.ENV_TYPE.ENV_DEVELOP ? "01" : "00";
//                    if (TextUtils.isEmpty(res.data)) {
//                        showMessage("订单异常");
//                        return;
//                    }
//                    //UPPayAssistEx.startPay(getActivity(), null, null, res.data, mode);
//                }));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            // 支付成功后，extra中如果存在result_data，取出校验
            // result_data结构见c）result_data参数说明
            if (data.hasExtra("result_data")) {
                String sign = data.getExtras().getString("result_data");
                // 验签证书同后台验签证书
                // 此处的verify，商户需送去商户后台做验签
//                if (verify(sign)) {
                //验证通过后，显示支付结果
              //  showMessage(" 支付成功！ ");
//                } else {
                // 验证不通过后的处理
                // 建议通过商户后台查询支付结果
//                }
            } else {
                // 未收到签名信息
                // 建议通过商户后台查询支付结果
            }
            getActivity().finish();
        } else if (str.equalsIgnoreCase("fail")) {
            //showMessage(" 支付失败！ ");
        } else if (str.equalsIgnoreCase("cancel")) {
           // showMessage(" 你已取消了本次订单的支付！ ");
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void startFriendPay() {
       // CommonActivity.startWithParam(getContext(), CommonActivity.ACTIVITY_FRIEND_PAY, "" + orderInfo.id);
    }

    ///PasswordInputPopup popup = null;

    private void banlancePay(String p) {
//        GvgModel.getInstance().availablePay("" + orderInfo.id, p)
//                .subscribe(new RxSubscriber<BaseResponse<Object>>(this, res -> {
//                //    showMessage("支付成功");
////                    if (popup != null) {
////                        popup.dismiss();
////                    }
//                    getActivity().finish();
//                }));
    }

    private void wechart() {

//        GvgModel.getInstance().wxPay("" + orderInfo.id)
//                .subscribe(new RxSubscriber<BaseResponse<WechartPay>>(this, res -> {
////                    GloblaData.setWechartPay(1);
////                    WechartUtil.getInstance().pay(res.data);
//                }));
    }

    private void alipay() {
//        GvgModel.getInstance().alipayPay("" + orderInfo.id)
//                .subscribe((Observer<? super BaseResponse<AlipayInfo>>) new RxSubscriber<BaseResponse<AlipayInfo>>(this, res -> {
//                    new Thread(() -> {
//                        PayTask alipay = new PayTask(getActivity());
//                        Map<String, String> result = alipay.payV2(res.data.orderInfo, true);
//
//                        Message msg = new Message();
//                        msg.what = ALI_PAY_FLAG;
//                        msg.obj = result;
//                        mHandler.sendMessage(msg);
//                    }).start();
//                }));
    }
}
